package com.ktgj.common.map;

import com.alibaba.fastjson.JSONObject;
import com.ktgj.common.core.utils.HttpClientUtil;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;

public class GaoDeUtil {

    //private final String GaoDeKey = "87378a4dc649aa04e01267b4fb56b091";  //吕英彪
    //private final String GaoDeKey = "282fc9c6fd0381c565ff8c40d1753bbb";  //初艳东
    //private final String GaoDeKey = "1613a231cdab0a87564cfc4747ead2b1";  //杨正冉
    private final String GaoDeKey = "ba584cc7cbc1494d9491e37f7b49b920";  //金色世纪

    /**
     * 根据经纬度获取所在城市
     * @param coordinate 经纬度 经纬度之间用","分割 小数点后不要超过 6 位 例：116.016032,39.017932
     * @return 成功：“城市名称”; 失败：“error"
     */
    public String getCityByCoordinate(String coordinate) {
        String url = "https://restapi.amap.com/v3/geocode/regeo?key=" + GaoDeKey + "&location=" + coordinate;
        String jsonStr = HttpClientUtil.doGet(url);
        JSONObject data = JSONObject.parseObject(jsonStr);
        if (data.getString("status").equals("0"))
            return "error";
        JSONObject regeocode = data.getJSONObject("regeocode");
        JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
        if (addressComponent.getString("city").equals("") || addressComponent.getString("city").equals("[]"))
            return addressComponent.getString("province");
        return addressComponent.getString("city");
    }

    public double getDistanceMeter(String gpsFromCoordinate, String gpsToCoordinate)
    {
        String[] gpsFromArr = gpsFromCoordinate.split(",");
        String[] gpsToArr = gpsToCoordinate.split(",");
        GlobalCoordinates gpsFrom = new GlobalCoordinates(new Double(gpsFromArr[1]).doubleValue(), new Double(gpsFromArr[0]).doubleValue());
        GlobalCoordinates gpTo = new GlobalCoordinates(new Double(gpsToArr[1]).doubleValue(), new Double(gpsToArr[0]).doubleValue());

        //创建GeodeticCalculator，调用计算方法，传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere, gpsFrom, gpTo);

        return geoCurve.getEllipsoidalDistance();
    }
//850米
    public static void main(String[] args) {
        GaoDeUtil gaoDeUtil = new GaoDeUtil();
        System.out.println(gaoDeUtil.getDistanceMeter("116.391278,39.907472","116.401216,39.90778"));
    }
}
